<template>
  <div class="head-container">
    <el-input v-model="treeboxName" class="mb-20px" clearable placeholder="请输入用例集名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
  <div class="head-container">
    <el-tree :data="treeboxList" ref="treeRef" node-key="id" default-expand-all :expand-on-click-node="false"
      :filter-node-method="filterNode" :props="defaultProps" class="tree" :highlight-current="true" :indent="22"
      @node-click="handleNodeClick">
      <template #default="{ node, data }">
        <!-- 非叶子 -->
        <span v-if="!node.isLeaf" style="display: flex; align-items: center">
          <span @click.stop="node.expanded = !node.expanded">
            <el-icon v-if="node.expanded" style="margin: 0 6px 0 2px" size="16">
              <FolderOpened />
            </el-icon>
            <el-icon v-else style="margin: 0 6px 0 2px" size="16">
              <Folder />
            </el-icon>
          </span>
          <small>{{ node.label }}</small>
          <span v-if="data.caseNum > 0" class="num"> （{{ data.caseNum }}） </span>
        </span>
        <!-- 叶子 -->
        <span v-else style="display: flex; align-items: center">
          <!-- <el-icon style="margin: 0 6px 0 2px" size="16">
            <Document />
          </el-icon> -->
          <el-icon style="margin: 0 6px 0 2px" size="16">
            <FolderOpened />
          </el-icon>
          <small>{{ node.label }}</small>
          <span v-if="data.caseNum > 0" class="num"> （{{ data.caseNum }}） </span>
        </span>
        <!-- 操作 -->
        <span v-if="isRootNode(data)">
          <a @click="openForm('create', data)" style="margin-left: 8px">
            <el-icon>
              <CirclePlus />
            </el-icon></a>
        </span>
        <span v-else>
          <a @click="openForm('update', data)">
            <el-icon>
              <Edit />
            </el-icon></a>
          <a style="margin-left: 8px" @click="openForm('create', data)">
            <el-icon>
              <CirclePlus />
            </el-icon></a>
          <a style="margin-left: 8px" @click="handleDelete(data.id)">
            <el-icon>
              <Delete />
            </el-icon>
          </a>
        </span>
      </template>
    </el-tree>
  </div>
  <!-- 表单弹窗：添加/修改 -->
  <TestboxForm ref="formRef" @success="getTree" />
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
import * as UseCaseApi from '@/api/usecase'
import TestboxForm from './TestboxForm.vue'
import { Edit, CirclePlus, Delete, FolderOpened, Folder, Document } from '@element-plus/icons-vue'

defineOptions({ name: 'TestboxFormTree' })

import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
let projectId = computed(() => appStore.getSelectProject)
const treeboxName = ref('')
const treeboxList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultProps = {
  children: 'children',
  label: 'name'
}

watch(projectId, (newValue) => {
  getTree()
})


/** 获得用例集树 */
const getTree = async () => {
  const data = await UseCaseApi.getTestboxTree({ projectId: projectId.value })
  treeboxList.value = data ? [data] : []
}

defineExpose({ getTree })

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 判断根节点 */
const isRootNode = (data) => {
  return data.isRoot
}

/** 计算子节点 */
const getChildCount = (nodeData) => {
  if (!nodeData.children || nodeData.children.length === 0) {
    return 0
  }
  return nodeData.children.length
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, data?: any) => {
  formRef.value.open(type, data, projectId)
}

/** 删除按钮操作 */
const emits = defineEmits(['node-click', 'refresh'])
const handleDelete = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UseCaseApi.deleteTestbox(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getTree()
    emits('refresh')
  } catch { }
}

/** 处理用例集被点击 */
const handleNodeClick = async (data) => {
  emits('node-click', data)
}

/** 监听deptName */
watch(treeboxName, (val) => {
  treeRef.value!.filter(val)
})

/** 初始化 */
onMounted(async () => {
  if (projectId.value) {
    getTree()
  }
})
</script>

<style scoped lang="scss">
.num {
  color: var(--el-color-primary);
  border-radius: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  // margin: 0 0px 0 10px;
  font-size: 12px;
}

:deep(.el-tree) {
  padding: 10px 10px 10px 0;

  .el-tree-node {
    .el-tree-node__content {
      display: flex;
      justify-content: space-between;
    }

    i.el-tree-node__expand-icon {
      svg {
        display: none;
      }
    }

    i.el-tree-node__expand-icon {
      display: none;
    }
  }

  .el-tree-node.is-current {
    .el-tree-node__content {
      small {
        color: #5e7ce0;
      }
    }

    .el-tree-node__children {
      small {
        color: unset;
      }
    }
  }

  /* ^ 树节点 */
  .el-tree-node {
    position: relative;
    width: auto;
    padding-left: 13px;

    &::before {
      width: 1px;
      height: 100%;
      content: '';
      position: absolute;
      top: -38px;
      bottom: 0;
      left: 0;
      right: auto;
      border-width: 1px;
      border-left: 1px solid #b8b9bb;
    }

    &::after {
      width: 13px;
      height: 13px;
      content: '';
      position: absolute;
      z-index: 0;
      left: 0;
      right: auto;
      top: 12px;
      bottom: auto;
      border-width: 1px;
      border-top: 1px solid #b8b9bb;
    }

    .el-tree-node__content {
      position: relative;
      z-index: 1;
      // color: #000;
      padding-left: 0 !important;
    }

    .el-tree-node__children {
      padding-left: 12px;
    }

    &:last-child::before {
      height: 50px;
    }
  }

  >.el-tree-node {
    padding-left: 0;

    &::before {
      border-left: none;
    }

    &::after {
      border-top: none;
    }
  }
}
</style>
